# handle_post_posterous.py - Handle queue requests to post to Posterous.
# Copyright 2010 Rob Myers <rob@robmyers.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging
import post_data
import simplejson
import traceback
import urllib
import urllib2
import yaml

import wsgiref.handlers
from google.appengine.runtime import DeadlineExceededError
from google.appengine.ext import webapp

POSTEROUS_POST_URL = 'http://posterous.com/api/newpost'

class PosterousWorker(webapp.RequestHandler):
    def message_body(self, data):
        message = ''
        if data.embed_html:
            message += data.embed_html + '<br />'
        elif data.image_url:
            message += '<img src="' + data.image_url + '" /><br />'
            
        message += '<a href="' + data.source_url + '">' + \
            data.title + '</a><br />'
        if data.description:
            message += data.description + '<br />'
        if data.user_name:
            message += 'By '
            if data.user_url:
                message += '<' + ">"+ data.user_name +'</a><br />'
            else:
                message += data.user_name
        return message

    def tags(self, keywords):
        return ','.join(keywords)

    def post(self):
        dgr_yaml_path = self.request.get('dgr-yaml-path')
        data_json = self.request.get('post-data')
        keywords = simplejson.loads(self.request.get('emotions'))
        if(dgr_yaml_path and data_json):
            try:
                logging.info('Posting to Posterous')
                config = yaml.safe_load(file(dgr_yaml_path, 'r'))
                data = post_data.PostData().from_json(data_json)
                password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
                password_manager.add_password(None, 
                                              POSTEROUS_POST_URL, 
                                              config['posterous_username'], 
                                              config['posterous_password'])
                auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
                opener = urllib2.build_opener(auth_handler)
                urllib2.install_opener(opener)
                params = urllib.urlencode({'title': data.title, 
                                           'body': self.message_body(data),
                                           'tags': self.tags(keywords)})
                result = urllib2.urlopen(POSTEROUS_POST_URL, params)
                logging.info('Posted to Posterous')
            except Exception, e:
                logging.error(type(e))
                logging.error(e)
                logging.error(traceback.format_exc())

def main():
    wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
                ('/post-posterous', PosterousWorker)], debug=True))
    
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    main()
